package com.cloud.common;


import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


public class CloudUserUtils {

    protected static Logger logger = LoggerFactory.getLogger(CloudUserUtils.class);

    public static String getUserName() throws Exception {
        Claims claims = getClaims();
        String userName = (String)claims.get("userName");
        logger.info("----------------CloudUserUtils-------->userName:"+userName);
        return userName;

    }
    public static Long getUserId() throws Exception {
        Claims claims = getClaims();
        Integer id = (Integer) claims.get("id");
        logger.info("----------------CloudUserUtils-------->userId:"+id);
        return id.longValue();
    }

    private static Claims getClaims() throws Exception {
        HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authToken = request.getHeader("authorization");
        Claims claims = JwtUtils.checkJWT(authToken);
        logger.info("----------------getRequest-------->authToken:"+authToken);
        if(null == claims){
            throw new Exception("校验登陆失败");
        }
        return claims;
    }

}
